<?php
declare(strict_types=1);

namespace App\Controller\Ws;

use App\Support\WebSocket;
use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\Di\Annotation\Inject;
use Swoole\Http\Request;
use Swoole\Server;
use Swoole\Websocket\Frame;
use Swoole\WebSocket\Server as WebSocketServer;

class WebSocketController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{


    /**
     * @Inject()
     * @var  WebSocket
     */
    public $websocket;

    public function onMessage($server, Frame $frame): void
    {

        $result = json_decode($frame->data, true);

        $userId = $this->websocket->getUidByFd(strval($frame->fd));
        if (isset($result['event']) && $result['event'] == 'heartbeat') {
            $data = [
                'event' => 'heartbeat',
                'content' => [
                    'message' => 'pong',
                    'uid' => intval($userId),
                    'fd' => $frame->fd
                ]
            ];
            $server->push($frame->fd, json_encode($data));
            return;
        }
        $data = [
            'event' => 'heartbeat',
            'content' => [
                'message' => 'test',
                'uid' => intval($userId),
                'fd' => $frame->fd
            ]
        ];

        $server->push($frame->fd, json_encode($data));
    }

    public function onClose($server, int $fd, int $reactorId): void
    {
        $userId = $this->websocket->getUidByFd(strval($fd));
        if ($userId) {
            $this->websocket->unBind($userId, $fd);
        }
        logger()->info('ws连接关闭', [$userId]);

    }

    public function onOpen($server, Request $request): void
    {

        $userId = auth('jwt')->user()->getId();


        //判断是否有连接过
        $fd  = $this->websocket->getFdByUid($userId);

        if ($fd){
            var_dump($fd);
            $rel = $server->disconnect(intval($fd));
            var_dump($rel);
        }



        //绑定 用户ID和FD关系
        $this->websocket->bind($userId, $request->fd);
        $data = [
            'event' => 'open',
            'content' => [
                'uid' => intval($userId),
                'fd' => $request->fd
            ]
        ];

        $server->push($request->fd, json_encode($data));
    }
}
